// API基础配置
const API_BASE_URL = 'http://localhost:8124/api'
// const API_BASE_URL = 'https://api.longwingstech.cn/api'

// 通用请求函数
async function request<T>(
  endpoint: string,
  options: RequestInit = {}
): Promise<T> {
  const url = `${API_BASE_URL}${endpoint}`
  
  const defaultHeaders = {
    'Content-Type': 'application/json',
  }

  // 添加认证token
  const token = localStorage.getItem('token')
  if (token) {
    defaultHeaders['Authorization'] = `Bearer ${token}`
  }

  const config: RequestInit = {
    ...options,
    headers: {
      ...defaultHeaders,
      ...options.headers,
    },
  }

  try {
    const response = await fetch(url, config)
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const data = await response.json()
    
    // 检查业务状态码
    if (data.code !== 0) {
      throw new Error(data.message || '请求失败')
    }
    
    return data
  } catch (error) {
    console.error('API request failed:', error)
    throw error
  }
}

// 用户登录请求接口
export interface LoginRequest {
  username: string
  password: string
}

// 用户登录响应接口
export interface LoginResponse {
  code: number
  data: {
    token: string
    expireTime: number
    user: {
      id: number
      username: string
      nickname: string
      remark: string
      email: string
      mobile: string
      sex: number
      avatar: string
      status: number
    }
  }
  message: string
}

// 用户注册请求接口
export interface RegisterRequest {
  username: string
  password: string
  confirmPassword: string
  remark: string
  email: string
  code: string
}

// 用户注册响应接口
export interface RegisterResponse {
  code: number
  data: boolean
  message: string
}

// 用户更新请求接口
export interface UpdateUserRequest {
  username?: string
  nickname?: string
  avatar?: string
  password?: string
  sex?: number
  checkPassword?: string
  mobile?: string
  remark?: string
  email?: string
  code?: string
}

// 用户更新响应接口
export interface UpdateUserResponse {
  code: number
  data: boolean
  message: string
}

// 获取验证码响应接口
export interface GetCodeResponse {
  code: number
  data: boolean
  message: string
}

// 获取当前用户信息响应接口
export interface CurrentUserResponse {
  code: number
  data: {
    id: number
    username: string
    nickname: string
    remark: string
    email: string
    mobile: string
    sex: number
    avatar: string
    status: number
  }
  message: string
}

// API服务类
export class AuthAPI {
  // 用户登录
  static async login(data: LoginRequest): Promise<LoginResponse> {
    return request<LoginResponse>('/auth/login', {
      method: 'POST',
      body: JSON.stringify(data),
    })
  }

  // 用户注册
  static async register(data: RegisterRequest): Promise<RegisterResponse> {
    return request<RegisterResponse>('/auth/register', {
      method: 'POST',
      body: JSON.stringify(data),
    })
  }

  // 获取验证码
  static async getCode(email: string): Promise<GetCodeResponse> {
    return request<GetCodeResponse>(`/auth/getCode?email=${encodeURIComponent(email)}`, {
      method: 'GET',
    })
  }

  // 获取当前用户信息
  static async getCurrentUser(): Promise<CurrentUserResponse> {
    return request<CurrentUserResponse>('/auth/currentUser', {
      method: 'GET',
    })
  }

  // 用户退出
  static async logout(): Promise<{ code: number; data: boolean; message: string }> {
    return request('/auth/logout', {
      method: 'POST',
    })
  }

  // 更新用户信息
  static async updateUser(data: UpdateUserRequest): Promise<UpdateUserResponse> {
    return request<UpdateUserResponse>('/auth/update', {
      method: 'POST',
      body: JSON.stringify(data),
    })
  }
}

// AI聊天API类
export class ChatAPI {
  // 灵溪医疗助手SSE聊天
  static createMedicalChatStream(message: string, chatId: string): EventSource {
    const token = localStorage.getItem('token')
    const url = new URL(`${API_BASE_URL}/ai/doctor_app/chat/sse`)
    
    // 添加查询参数
    url.searchParams.append('message', message)
    url.searchParams.append('chatId', chatId)
    url.searchParams.append('Authorization', `Bearer ${token}`)
    
    console.log('Creating SSE connection to:', url.toString()) // 调试日志
    
    const eventSource = new EventSource(url.toString())
    return eventSource
  }

  // 超级智能体SSE聊天
  static createSuperAgentStream(message: string, chatId: string): EventSource {
    const token = localStorage.getItem('token')
    const url = new URL(`${API_BASE_URL}/ai/super/agent/sse`)
    
    // 添加查询参数
    url.searchParams.append('message', message)
    url.searchParams.append('chatId', chatId)
    url.searchParams.append('Authorization', `Bearer ${token}`)
    
    console.log('Creating SSE connection to:', url.toString()) // 调试日志
    
    const eventSource = new EventSource(url.toString())
    return eventSource
  }

  // 生成标题
  static async generateTitle(message: string, chatId: string): Promise<{ code: number; data: string; message: string }> {
    const url = `/ai/genTitle?message=${encodeURIComponent(message)}&chatId=${encodeURIComponent(chatId)}`
    return request(url, {
      method: 'GET',
    })
  }
}

export default AuthAPI
